package com.semanticweb.project.search.searchers;

import java.io.File;
import java.io.IOException;
import java.util.ResourceBundle;

import org.apache.lucene.index.Term;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

public class BooleanSearcher {

    private static final ResourceBundle SEARCH_BUNDLE = ResourceBundle
            .getBundle("com.semanticweb.project.search.config.lucene");

    public static final int AND_CONDITION = 0;
    public static final int OR_CONDITION = 1;

    public static TopDocs search(final String fieldA, final String termA, final String fieldB, final String termB,
            final int condition, final int returnCount) {
        if (fieldA == null || termA == null || fieldB == null || termB == null) {
            return null;
        }

        final TermQuery query1 = new TermQuery(new Term(fieldA, termA));
        final TermQuery query2 = new TermQuery(new Term(fieldB, termB));

        final BooleanQuery query = new BooleanQuery();
        if (condition == AND_CONDITION) {
            query.add(query1, Occur.MUST);
            query.add(query2, Occur.MUST);
        } else if (condition == OR_CONDITION) {
            query.add(query1, Occur.SHOULD);
            query.add(query2, Occur.SHOULD);
        } else {
            return null;
        }
        final File indexDir = new File(SEARCH_BUNDLE.getString("indexDir"));
        try {
            final Directory indexDirectory = FSDirectory.open(indexDir);
            final IndexSearcher indexSearcher = new IndexSearcher(indexDirectory);
            indexSearcher.close();
            return indexSearcher.search(query, returnCount);
        } catch (final IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}